<?php

namespace App\Http\Controllers\Backend;

use App\User;
use Illuminate\Http\Request;
use App\Model\Order;
use App\Model\Product;
use App\Model\OrderProduct;
use App\Model\OrderChangeLog;

use App\Model\BistroIncomeDay;
use App\Model\BistroIncomeMonth;

use App\Model\ProductSaleDay;
use App\Model\ProductSaleMonth;

use App\Transformers\OrderTransformer;
use App\Transformers\OrderProductTransformer;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class OrderController extends Controller
{
    /**
     * 店铺的点餐列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request) {
        $bistro = $request->user('bistro');

        $order_number = $request->input('order_number');
        $start = $request->input('start');
        $end = $request->input('end');
        $date = date('Y-m-d');
//        $status = ['un_pay', 'payed', 'shiped_not_pay', 'shiped'];
//        $status_not = '';
        //退菜区
        $orders = Order::where('bistro_id', $bistro->id)
                            ->where('status', '<>', 'complete')
//                            ->orWhere('order_status', '<>', 'ordered')
                            ->orderNumber($order_number)
                            ->totalAmount($start, $end)
                            ->date($date)
//                            ->status($status)
//                            ->orderby('id', 'desc')
                            ->paginate(20);
        $data['data'] = [
            'orders' => $this->factalPaginator($orders, new OrderTransformer())
        ];
        return $this->apiSuccess($data);
    }

    /**
     * 所有订单列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function orderAll(Request $request) {
        $bistro = $request->user('bistro');

        $order_number = $request->input('order_number');
        $sort_number = $request->input('sort_number');
        $start = $request->input('start');
        $end = $request->input('end');
        $status = $request->input('status');

        $orders = Order::where('bistro_id', $bistro->id)
            ->status($status)
            ->orderNumber($order_number)
            ->SortNumber($sort_number)
            ->totalAmount($start, $end)
            ->orderby('id', 'desc')
            ->paginate(10);
        $data['data'] = [
            'orders' => $this->factalPaginator($orders, new OrderTransformer())
        ];
        return $this->apiSuccess($data);
    }

    /**
     * 订单详情
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function detail($id) {
        $order = Order::findorfail($id);
        $order_products = OrderProduct::where('order_id', $order->id)->where('status', '<>', 'return')->get();
        $total_amount = 0;
        foreach ($order_products as $op) {
            $total_amount += $op['total_amount'] * 1;
        }
        $order_returns = OrderProduct::where('order_id', $order->id)->where('status', 'return')->get();
        foreach ($order_returns as $op2) {
            $total_amount += $op2['total_amount'] * 1;//total_amount记成负的
        }
        $data['data'] = [
            'order' => $this->fractalItem($order, new OrderTransformer()),
            'total_amount' => $total_amount,
            'order_products' => $this->fractalItems($order_products, new OrderProductTransformer()),
            'order_returns' => $this->fractalItems($order_returns, new OrderProductTransformer()),
        ];
        return $this->apiSuccess($data);
    }

    /**
     * 直接修改订单为上菜成功
     * @param Request $request
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function updateOrderOrder(Request $request, $id) {//上菜
        $bistro = $request->user('bistro');
        $order = Order::findorfail($id);
        //上菜未付款
        $order_products = OrderProduct::where('order_id', $order->id)->where('status', '<>', 'return')->get();
        DB::beginTransaction();
        try {
            $order->order_status = 'ordered';
            $order->save();
            foreach ($order_products as $od) {
                if($od->status != 'done'){
                    $od->status = 'done';
                    $od->serve_num = $od->num;//数量 + 退回数量
                    $od->save();
                }
            }
            DB::commit();
        } catch (\Exception $e) {
            DB::rollback();
            return $this->apiError($e->getMessage());
        }
//        if($order->status == 'payed') {
//            $order->status = 'shiped';
//            $order->save();
//        }else if ($order->status == 'un_pay') {//shiped_not_pay
//            $order->status = 'shiped_not_pay';
//            $order->save();
//        }else{
//            return $this->apiError('不可修改');
//        }
        return $this->apiSuccess();
    }

    /**
     * 订单完成
     * @param Request $request
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function completeOrder(Request $request, $id) {
        $bistro = $request->user('bistro');
        DB::beginTransaction();
        try {
            $order = Order::findorfail($id);
            $order->status = 'complete'; //已支付
            $order->order_status = 'ordered'; //已上菜
            $order->save();
            $date = date('Y-m-d');
            $month = date('Y-m');
            $year = date('Y');

            //查询订单中商品 是否有代金金额 有 就添加用户代金金额
            $order_products = OrderProduct::where('order_id', $order->id)->get();
            $total_amount = 0;

            foreach ($order_products as $op) {
                //product 减少库存
                $product = Product::findorfail($op->product_id);
                $product->sale_count = $product->sale_count * 1 + $op->num * 1;
                $product->save();

                //商品日销售
                $product_sale_day = ProductSaleDay::date($date)->productId($op->product_id)->first();
                if(empty($product_sale_day)) {
                    $product_sale_day = new ProductSaleDay();
                    $product_sale_day->product_id = $op->product_id;
                    $product_sale_day->sale_count = 0;
                    $product_sale_day->total_amount = 0;
                    $product_sale_day->date = $date;
                    $product_sale_day->product_name = $product->name;
                }
                $product_sale_day->sale_count = $product_sale_day->sale_count * 1 + $op->num * 1;
                $product_sale_day->total_amount = $product_sale_day->total_amount * 1 + $op->total_amount * 1;
                $product_sale_day->save();

                //商品月销售
                $product_sale_month = ProductSaleMonth::month($month)->productId($op->product_id)->first();
                if(empty($product_sale_month)) {
                    $product_sale_month = new ProductSaleMonth();
                    $product_sale_month->product_id = $op->product_id;
                    $product_sale_month->sale_count = 0;
                    $product_sale_month->total_amount = 0;
                    $product_sale_month->month = $month;
                    $product_sale_month->year = $year;
                    $product_sale_month->product_name = $product->name;
                }
                $product_sale_month->sale_count = $product_sale_month->sale_count * 1 + $op->num * 1;
                $product_sale_month->total_amount = $product_sale_month->total_amount * 1 + $op->total_amount * 1;
                $product_sale_month->save();

                $total_amount += $op->total_amount;

            }

            //店铺日收益计算
            $bistro_income_day = BistroIncomeDay::date($date)->bistroId($order->bistro_id)->first();
            if(empty($bistro_income_day)) {
                $bistro_income_day = new BistroIncomeDay();
                $bistro_income_day->bistro_id = $order->bistro_id;
                $bistro_income_day->date = $date;
                $bistro_income_day->income = 0;
                $bistro_income_day->outcome = 0;
            }
            $bistro_income_day->income = $bistro_income_day->income * 1 + $total_amount * 1;
            $bistro_income_day->save();
////
            //店铺月收益计算
            $bistro_income_month = BistroIncomeMonth::month($month)->bistroId($order->bistro_id)->first();
            if(empty($bistro_income_month)) {
                $bistro_income_month = new BistroIncomeMonth();
                $bistro_income_month->bistro_id = $order->bistro_id;
                $bistro_income_month->month = $month;
                $bistro_income_month->year = $year;
                $bistro_income_month->income = 0;
                $bistro_income_month->outcome = 0;
            }
            $bistro_income_month->income = $bistro_income_month->income * 1 + $total_amount * 1;
            $bistro_income_month->save();
////
////
            $user = User::findorfail($order->user_id);

            //如果这个桌子上请客的直接删掉请客单
            $now_open_id_str = Redis::get('orderdinner:position_id||'.$order->position_id);
            if(empty($now_open_id_str)) {
                $now_open_id_s = [];
            }else{
                $now_open_id_s = json_decode($now_open_id_str, true);
            }

            if(in_array($user->open_id, $now_open_id_s)) {
                $key = array_search($user->open_id, $now_open_id_s);
                unset($now_open_id_s[$key]);
                $now_open_id_sstr = json_decode($now_open_id_s);
                Redis::setex('orderdinner:position_id||'.$order->position_id, $now_open_id_sstr);//付款成功，请客结束
            }
//
            DB::commit();
        } catch (\Exception $e) {
            DB::rollback();
            return $this->apiError($e->getMessage());
        }

        return $this->apiSuccess();
    }

    /**
     * 上菜
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function serveOrderProduct(Request $request, $id) {//订单商品id
        $order_product = OrderProduct::findorfail($id);
        DB::beginTransaction();
        try {
            $serve_num = $order_product->serve_num * 1 + $request->input('serve_num') * 1;
            if($serve_num > $order_product->num) return $this->apiError('上菜数量有误');
            if($serve_num == $order_product->num) {
                $order_product->status = 'done';
            }
            $order_product->serve_num = $serve_num;
            $order_product->save();

            DB::commit();
        } catch (\Exception $e) {
            DB::rollback();
            return $this->apiError($e->getMessage());
        }

        return $this->apiSuccess();
    }

    /**
     * 退菜
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function returningVegetables(Request $request, $id) {
        $bistro = $request->user('bistro');
        $return_num = $request->input('return_num');//退菜数量
        $reason = $request->input('reason');//退菜原因

        $order_product = OrderProduct::findorfail($id);
        $order = Order::findorfail($order_product->order_id);

        //先看退菜数量合法不
        $order_return_number = OrderProduct::where('order_id', $order_product->order_id)
                                            ->where('product_id', $order_product->product_id)
                                            ->where('status', 'return')->sum('num');
//        //退菜数量
        $return_num_total = $order_return_number * -1 + $return_num * 1;
        if($return_num_total > $order_product->num) {// 不能大于总数量
            return $this->apiError('退菜数量有误');
        }
        DB::beginTransaction();
        try {
            $return_order_product = new OrderProduct();
            $return_order_product->order_id = $order_product->order_id;
            $return_order_product->product_id = $order_product->product_id;
            $return_order_product->total_amount = $order_product->price * $return_num * -1;
            $return_order_product->num = $return_num * -1;
            $return_order_product->information = $order_product->information;
            $return_order_product->status = 'return';
            $return_order_product->date = date('Y-m-d');
            $return_order_product->price = $order_product->price;
            $return_order_product->save();

            $order_change_log = new OrderChangeLog();
            $order_change_log->order_id = $order_product->order_id;
            $order_change_log->total_amount = $order_product->price * $return_num * -1;
            $order_change_log->status = 'return';//取消了
            $order_change_log->reason = $reason;
            $order_change_log->save();

            DB::commit();
        } catch (\Exception $e) {
            DB::rollback();
            return $this->apiError($e->getMessage());
        }
//        DB::beginTransaction();
//        try {
////            if($return_num_total == $order_product->num) {
////                $order = Order::findorfail($order_product->order_id);
////                $order_product->status = 'cancel';
////                $order_product->save();
////            }
////
////            //订单为已完成 那直退菜 直接修改金额
////            if($order->status == 'complete') {
////                $product = Product::findorfail($order_product->product_id);
////                $product->sale_count = $product->sale_count * 1 - $order_product->num;
////                $product->save();
////                $today = $order_product->date;
////                $this_month = date('Y-m', strtotime($today));
////
////                //店铺统计
////                $bistro_income_day = BistroIncomeDay::where('bistro_id', $order->bistro_id)->where('date', $today)->first();
////                $bistro_income_month = BistroIncomeMonth::where('bistro_id', $order->bistro_id)->where('month', $this_month)->first();
////
////                if(empty($bistro_income_day)) return $this->apiError('未找到店铺日收益');
////                if(empty($bistro_income_month)) return $this->apiError('未找到店铺月收益');
////
////                $bistro_income_day->outcome = $bistro_income_day->outcome *1 + $order_product->total_amount * 1;
////                $bistro_income_day->save();
////
////                $bistro_income_month->outcome = $bistro_income_month->outcome * 1 + $order_product->price * $return_num;
////                $bistro_income_month->save();
////
////                //商品统计
////                $product_sale_day = ProductSaleDay::where('product_id', $product->id)->where('date', $today)->first();
////
////                if(empty($product_sale_day)) return $this->apiError('商品日统计不存在');
////
////                $product_sale_day->sale_count = $product_sale_day->sale_count * 1 - $return_num * 1;
////                $product_sale_day->total_amount = $product_sale_day->total_amount * 1 - $order_product->price * $return_num;
////                $product_sale_day->save();
////
////                $product_sale_month = ProductSaleMonth::where('product_id', $product->id)->where('month', $this_month)->first();
////
////                if(empty($product_sale_month)) return $this->apiError('商品月统计不存在');
////                $product_sale_month->sale_count = $product_sale_month->sale_count * 1 - $product_sale_month->num * 1;
////                $product_sale_month->total_amount = $product_sale_month->total_amount * 1 - $product_sale_month->total_amount * 1;
////                $product_sale_month->save();
////            }
////
////            $order->total_amount = $order->total_amount * 1 - $order_product->price * $return_num;
////            $order->save();
////
////            $order_product->return_num = $return_num_total;
////            $order_product->total_amount = $order_product->total_amount - $order_product->price * $return_num;
////            $order_product->save();
////
////            $order_change_log = new OrderChangeLog();
////            $order_change_log->order_id = $order_product->order_id;
////            $order_change_log->total_amount = $order_product->price * $return_num * -1;
////            $order_change_log->status = 'cancel';//取消了
////            $order_change_log->reason = $reason;
////            $order_change_log->save();
//
//            DB::commit();
//        } catch (\Exception $e) {
//            DB::rollback();
//            return $this->apiError($e->getMessage());
//        }

        return $this->apiSuccess();
    }

    /**
     * 订单添加商品
     * @param Request $request
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function orderAddProduct(Request $request, $id) {
        $bistro = $request->user('bistro');
        $order = Order::bistroId($bistro->id)->where('id', $id)->first();
        $exchange_list = $request->input('exchange_list');
        $total_amount = 0;
        DB::beginTransaction();
        try {
            foreach ($exchange_list as $exc) {
                $op = OrderProduct::where('order_id', $order->id)->where('product_id', $exc['product_id'])->first();
                $product = Product::findorfail($exc['product_id']);
                if(empty($op)) {
                    $op = new OrderProduct();
                    $op->order_id = $order->id;
                    $op->product_id = $exc['product_id'];
                    $op->num = $exc['num'];
                    $op->total_amount = $exc['num'] * $product['discount'];
                    $op->information = json_encode($product);
                    $op->status = 'un_done';
                    $op->date = date('Y-m-d');
                }
                $op->num = $op->num * 1 + $exc['num'] * 1;
                $op->total_amount = $op->total_amount * 1 + $exc['num'] * $product['discount'];
                $op->status = 'un_done';
                $op->save();

                $total_amount = $total_amount * 1 + $product['discount'] * $exc['num'];
            }

            $order->total_amount = $order->total_amount * 1 + $total_amount;
            $order->save();

            DB::commit();
        } catch (\Exception $e) {
            DB::rollback();
            return $this->apiError($e->getMessage());
        }
        return $this->apiSuccess();
    }

    public function updateProduct(Request $request) {

        //被换的商品 + 数量
        $change_list = $request->input('change_list');

        //替换的商品 + 数量
        $changed_list = $request->input('changed_list');

        //然后改账

    }

    public function deleteOrder($id) {
        $order = Order::findorfail($id);
        $order->delete();
        return $this->apiSuccess();
    }
}
